package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderDetailService orderDetailService;
    /*
        生成订单的操作
     */
    @Transactional
    @Override
    public void submit(Orders orders) {
        //1.查询当前用户的购物车
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.get());
        List<ShoppingCart> list = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        //2.根据购物车中的数据，来完善订单数据
        //2.1设置订单号(雪花算法)
        long number = IdWorker.getId();//订单号
        orders.setNumber(String.valueOf(number));
        //2.2设置订单状态
        orders.setStatus(2);
        //2.3设置下单用户
        orders.setUserId(BaseContext.get());
        //2.4设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //2.5设置支付时间
        orders.setCheckoutTime(LocalDateTime.now());
        //2.6设置订单金额
        //2.6.1计算总金额
        BigDecimal count = new BigDecimal("0");
        for (ShoppingCart shoppingCart : list) {
            //单价
            BigDecimal amount = shoppingCart.getAmount();
            //数量
            BigDecimal numberBigDecimal = new BigDecimal(shoppingCart.getNumber());
            BigDecimal price = amount.multiply(numberBigDecimal);
            count = count.add(price);
        }
        //2.6.2设置总金额
        orders.setAmount(count);
        //2.7设置收货人的手机号
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        //2.8设置收货人地址
        orders.setAddress(addressBook.getDetail());
        //2.9设置当前用户的用户名
        User user = userService.getById(BaseContext.get());
        orders.setUserName(user.getName());
        //3.0设置收货人
        orders.setConsignee(addressBook.getConsignee());
        super.save(orders);

        //4.保存订单明细表，记录该订单购买的商品具体信息
        //4.1把购物车集合，转成订单明细集合
        List<OrderDetail> orderDetailList = list.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);//缺少orderId
            orderDetail.setOrderId(orders.getId());
            return orderDetail;
        }).collect(Collectors.toList());
        orderDetailService.saveBatch(orderDetailList);

        //5清空购物车
        LambdaUpdateWrapper<ShoppingCart> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,BaseContext.get());
        shoppingCartService.remove(wrapper);
    }

    /*
        分页查询订单和明细
     */
    @Override
    public Page<OrdersDto> page(Integer page, Integer pageSize) {
        //分页条件
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //当前用户条件
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId,BaseContext.get());
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        super.page(pageInfo,ordersLambdaQueryWrapper);
        Page<OrdersDto> pageDtoInfo = new Page<>(page, pageSize);
        //把订单分页数据转成Dto分页数据
        BeanUtils.copyProperties(pageInfo,pageDtoInfo,"records");
        //手动设置records
        List<OrdersDto> ordersDtoList = pageInfo.getRecords().stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            //缺少订单明细
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //select * from orderDetail  where order_id=?
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(list);
            return ordersDto;
        }).collect(Collectors.toList());
        pageDtoInfo.setRecords(ordersDtoList);
        return pageDtoInfo;
    }
}
